java如何在JTextPane中为文本和下划线设置不同的颜色?
刚刚尝试在JTextPane中给文本上色,但问题是文本和下划线不能有不同的颜色。我该怎么做,或者说这可能吗?下面的示例以红色打印所有文本和下划线
JTextPane pane = new JTextPane();
StyleContext context = new StyleContext();
Style style = pane.addStyle("Black", null);
StyleConstants.setAlignment(style, StyleConstants.ALIGN_RIGHT);
StyleConstants.setFontSize(style, 14);
StyleConstants.setSpaceAbove(style, 4);
StyleConstants.setSpaceBelow(style, 4);
StyleConstants.setForeground(style, Color.BLACK);
StyledDocument document = pane.getStyledDocument();
style = pane.addStyle("Red Underline", style);
StyleConstants.setForeground(style, Color.RED);
StyleConstants.setUnderline(style, true);
pane.getDocument().insertString(0, "Test String", style);
# 1 楼答案
基本上,您需要创建3个类:
您需要扩展javax.swing.text.LabelView以执行修改视图的操作(无论是否添加彩色下划线)。您将重写
paint(Graphics, Shape)
方法。您可以使用重写类中的此行访问属性-属性应该是执行文本附加操作(如添加下划线)的触发器getElement().getAttributes().getAttribute("attribute name");
您需要创建一个新的ViewFactory并覆盖
create
方法。在执行此操作时,处理所有元素类型是很重要的(否则,事情将无法正确显示)。您需要创建一个StyledEditorKit来告诉窗格使用哪个
ViewFactory
下面是一个简化且可运行的示例:
以下是指向另一个示例代码的链接:
http://java-sl.com/tip_colored_strikethrough.html
这个答案主要是为了子孙后代,我认为添加一个简化版本的链接代码和解释将有助于使事情更容易理解
# 2 楼答案
for example和for Html
Document
返回要查看的模型,可以确定行开始/结束的索引# 3 楼答案
这是我找到的解决方案
Underline StyleConstant in a different colour with AttributeSet
下面是示例代码的链接
http://java-sl.com/tip_colored_strikethrough.html
只需更改以下行即可解决此问题
而且效果很好